package com.harvey.metrics.metric.gauge;

import com.codahale.metrics.CachedGauge;
import com.codahale.metrics.ConsoleReporter;
import com.codahale.metrics.MetricRegistry;

import java.util.concurrent.TimeUnit;

/**
 * @author harvey
 * @Description
 * <p>
 *     当存在外部资源调用，如DB，第三方服务接口等。耗时。但是 监控程序不应该要对系统运行有太大影响！
 *
 *     使用CachedGauge，允许对实时性的要求不能太高。
 *
 * </p>
 * @date 2020-04-09 08:39
 * @since
 */

public class CachedGaugeExample {

    private final static MetricRegistry registry = new MetricRegistry();

    private final static ConsoleReporter reporter = ConsoleReporter.forRegistry(registry)
            .convertRatesTo(TimeUnit.SECONDS)
            .convertDurationsTo(TimeUnit.SECONDS)
            .build();


    public static void main(String[] args) throws InterruptedException {
        reporter.start(3, TimeUnit.SECONDS);

        registry.gauge("cached-db-size", () -> new CachedGauge<Long>(30, TimeUnit.SECONDS) {
            @Override
            protected Long loadValue() {
                return queryFromDB();
            }
        });


        Thread.currentThread().join();

    }


    private static long queryFromDB() {
        System.out.println("query from db");
        return System.currentTimeMillis();
    }


}
